from flask import Blueprint, request, jsonify
import openai
import json
import random
from datetime import datetime

ai_bp = Blueprint('ai', __name__)

@ai_bp.route('/generate-questions', methods=['POST'])
def generate_questions():
    """AI生成测试题目"""
    try:
        data = request.get_json()
        words = data.get('words', [])  # 单词列表
        question_count = data.get('count', 5)
        difficulty = data.get('difficulty', 'medium')
        
        if not words:
            return jsonify({'success': False, 'error': 'Words list is required'}), 400
        
        # 模拟AI生成题目（实际应该调用GPT API）
        questions = []
        question_types = ['multiple_choice', 'fill_blank', 'translation']
        
        for i in range(min(question_count, len(words))):
            word_data = words[i]
            question_type = random.choice(question_types)
            
            if question_type == 'multiple_choice':
                # 生成选择题
                question = {
                    'id': i + 1,
                    'type': 'multiple_choice',
                    'question': f'What does "{word_data["en"]}" mean?',
                    'options': [
                        {'id': 'A', 'text': word_data['zh']},
                        {'id': 'B', 'text': generate_distractor(word_data['zh'])},
                        {'id': 'C', 'text': generate_distractor(word_data['zh'])},
                        {'id': 'D', 'text': generate_distractor(word_data['zh'])}
                    ],
                    'correct_answer': 'A',
                    'word_id': word_data.get('id'),
                    'difficulty': difficulty
                }
            elif question_type == 'fill_blank':
                # 生成填空题
                example = word_data.get('examples', [{}])[0]
                sentence = example.get('en_sentence', f'This is a {word_data["en"]}.')
                blank_sentence = sentence.replace(word_data['en'], '____')
                
                question = {
                    'id': i + 1,
                    'type': 'fill_blank',
                    'question': f'Fill in the blank: {blank_sentence}',
                    'correct_answer': word_data['en'],
                    'word_id': word_data.get('id'),
                    'difficulty': difficulty
                }
            else:  # translation
                # 生成翻译题
                question = {
                    'id': i + 1,
                    'type': 'translation',
                    'question': f'Translate to English: {word_data["zh"]}',
                    'correct_answer': word_data['en'],
                    'word_id': word_data.get('id'),
                    'difficulty': difficulty
                }
            
            questions.append(question)
        
        return jsonify({
            'success': True,
            'data': {
                'questions': questions,
                'total_count': len(questions),
                'difficulty': difficulty
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@ai_bp.route('/generate-praise', methods=['POST'])
def generate_praise():
    """AI生成表扬文案"""
    try:
        data = request.get_json()
        performance_data = data.get('performance', {})
        student_name = data.get('student_name', 'Student')
        
        score = performance_data.get('score', 75)
        accuracy = performance_data.get('accuracy', 75)
        improvement = performance_data.get('improvement', 0)
        
        # 模拟AI生成个性化表扬文案
        praise_templates = {
            'excellent': [
                f"Outstanding work, {student_name}! Your {score}% score shows exceptional dedication to learning English.",
                f"Brilliant performance! {student_name}, you've achieved {score}% accuracy - keep up this amazing momentum!",
                f"Exceptional progress, {student_name}! Your consistent effort is paying off with a {score}% score."
            ],
            'good': [
                f"Great job, {student_name}! Your {score}% score demonstrates solid understanding and steady progress.",
                f"Well done! {student_name}, you're making good progress with {accuracy}% accuracy this week.",
                f"Nice work, {student_name}! Your {score}% performance shows you're on the right track."
            ],
            'fair': [
                f"Good effort, {student_name}! Your {score}% score shows you're learning. Keep practicing!",
                f"You're making progress, {student_name}! With {accuracy}% accuracy, you're building a strong foundation.",
                f"Keep it up, {student_name}! Your {score}% score shows dedication. Practice makes perfect!"
            ]
        }
        
        if score >= 85:
            category = 'excellent'
        elif score >= 70:
            category = 'good'
        else:
            category = 'fair'
        
        praise_text = random.choice(praise_templates[category])
        
        # 添加改进建议
        suggestions = []
        if accuracy < 80:
            suggestions.append("Focus on pronunciation practice to improve accuracy.")
        if improvement < 0:
            suggestions.append("Review previous mistakes to avoid repeating them.")
        else:
            suggestions.append("Continue your excellent learning habits!")
        
        return jsonify({
            'success': True,
            'data': {
                'praise_text': praise_text,
                'suggestions': suggestions,
                'category': category,
                'personalized': True
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@ai_bp.route('/recommend-study-plan', methods=['POST'])
def recommend_study_plan():
    """AI推荐个性化学习计划"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        current_level = data.get('level', 'beginner')
        weak_areas = data.get('weak_areas', [])
        study_time = data.get('daily_study_time', 30)  # minutes
        
        if not user_id:
            return jsonify({'success': False, 'error': 'User ID is required'}), 400
        
        # 模拟AI生成个性化学习计划
        base_plan = {
            'daily_words': max(5, min(20, study_time // 3)),
            'review_frequency': 'daily' if study_time >= 30 else 'every_other_day',
            'focus_areas': []
        }
        
        # 根据薄弱环节调整计划
        if 'pronunciation' in weak_areas:
            base_plan['focus_areas'].append({
                'area': 'pronunciation',
                'activities': ['follow_reading', 'pronunciation_practice'],
                'time_allocation': 40  # percentage
            })
        
        if 'vocabulary' in weak_areas:
            base_plan['focus_areas'].append({
                'area': 'vocabulary',
                'activities': ['word_cards', 'example_sentences'],
                'time_allocation': 35
            })
        
        if 'listening' in weak_areas:
            base_plan['focus_areas'].append({
                'area': 'listening',
                'activities': ['audio_practice', 'dictation'],
                'time_allocation': 25
            })
        
        # 生成具体的学习建议
        recommendations = [
            f"Study {base_plan['daily_words']} new words daily",
            f"Practice pronunciation for at least {int(study_time * 0.4)} minutes",
            "Review previous mistakes before learning new content",
            "Take weekly tests to track progress"
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'study_plan': base_plan,
                'recommendations': recommendations,
                'estimated_improvement': '15-25% in 4 weeks',
                'personalized': True
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@ai_bp.route('/analyze-mistakes', methods=['POST'])
def analyze_mistakes():
    """AI分析学习错误模式"""
    try:
        data = request.get_json()
        mistakes = data.get('mistakes', [])
        user_id = data.get('user_id')
        
        if not mistakes:
            return jsonify({'success': False, 'error': 'Mistakes data is required'}), 400
        
        # 模拟AI分析错误模式
        analysis = {
            'common_patterns': [],
            'difficulty_areas': [],
            'improvement_suggestions': []
        }
        
        # 分析错误类型
        error_types = {}
        for mistake in mistakes:
            error_type = mistake.get('error_type', 'pronunciation')
            error_types[error_type] = error_types.get(error_type, 0) + 1
        
        # 找出最常见的错误类型
        if error_types:
            most_common = max(error_types, key=error_types.get)
            analysis['common_patterns'].append({
                'type': most_common,
                'frequency': error_types[most_common],
                'description': f"Most frequent errors are in {most_common}"
            })
        
        # 生成改进建议
        if 'pronunciation' in error_types:
            analysis['improvement_suggestions'].append(
                "Focus on phonetic practice and use audio examples more frequently"
            )
        
        if 'spelling' in error_types:
            analysis['improvement_suggestions'].append(
                "Practice writing words multiple times to improve spelling accuracy"
            )
        
        if 'meaning' in error_types:
            analysis['improvement_suggestions'].append(
                "Study word meanings in context using example sentences"
            )
        
        return jsonify({
            'success': True,
            'data': analysis
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def generate_distractor(correct_answer):
    """生成干扰选项"""
    distractors = [
        "书本", "桌子", "椅子", "窗户", "门", "墙壁", "地板", "天花板",
        "汽车", "自行车", "飞机", "火车", "船", "公交车", "摩托车",
        "苹果", "香蕉", "橙子", "葡萄", "草莓", "西瓜", "梨",
        "猫", "狗", "鸟", "鱼", "马", "牛", "羊", "猪"
    ]
    
    # 过滤掉正确答案
    available_distractors = [d for d in distractors if d != correct_answer]
    return random.choice(available_distractors) if available_distractors else "其他选项"

